package com.soul.server.server;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mdoya
 * @version 1.0
 * @description: Rabbitmq消息中间件 生产者  根据RabbitMQ的api构建自己公共api
 */

@Slf4j
@Component
public class MqMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate; // RabbitTemplate 和 AmqpTemplate 同是RabbitMQ消息中间件自动注入方法使用

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     *
     * @param userId  登录用户id
     * @param type 对应operType表, 操作类型
     * @param key routingKey
     * @param busId 业务对象的id: 操作视频它就视频id, 操作的是动态它就是动态id
     */
    public void sendLogMessage(Long userId,String type,String key,String busId) {
        try {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userId",userId.toString());
            map.put("type",type);
            map.put("logTime", DateUtil.today());
            map.put("busId",busId);// 业务对象id
            String message = JSON.toJSONString(map);
            //{"busId":"61b8148b57b2867b8d706371","type":"0203",
            //"userId":"10012","logTime":"2021-12-22"}
            // public void convertAndSend(String exchange, String routingKey, Object object)
            rabbitTemplate.convertAndSend("soul.log.exchange", "log."+key,message);

        } catch (AmqpException e) {
            log.error("RabbitMQ发送消息失败: {},{},{},{}",userId, type, key, busId );
        }
    }

    //发送动态审核消息
    public void sendAudiMessage(String movementId) {
        try {
            rabbitTemplate.convertAndSend("soul.audit.exchange",  "audit.movement",movementId);
        } catch (AmqpException e) {
            log.error("RabbitMQ发送消息失败: 动态审核:{}", movementId);
        }
    }

}
